package com.dayu.springbootcache.config;

import com.dayu.springbootcache.entity.Department;
import com.dayu.springbootcache.entity.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.io.Serializable;
import java.net.UnknownHostException;

@Configuration
public class RedisConfig {//自定义对象序列化方法
    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> serializer =new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(serializer);//修改默认序列化
        return template;
    }
    @Bean
    public RedisTemplate<Object, Department> deptRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Department> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Department> serializer =new Jackson2JsonRedisSerializer<Department>(Department.class);
        template.setDefaultSerializer(serializer);//修改默认序列化
        return template;
    }
    @Primary//默认缓存管理器
    @Bean//自定义缓存管理器定制规则效果和上面一样重新修改了序列化方法
    public RedisCacheManager employeeCacheManager(RedisTemplate<Object,Employee> employeeRedisTemplate){
        RedisCacheManager cacheManager=new RedisCacheManager(employeeRedisTemplate);
        //key多了一个前缀
        //使用前缀,默认会将cacheName作为key的前缀
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }

    @Bean//自定义缓存管理器定制规则效果和上面一样重新修改了序列化方法
    public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate){
        RedisCacheManager cacheManager=new RedisCacheManager(deptRedisTemplate);
        //key多了一个前缀
        //使用前缀,默认会将cacheName作为key的前缀
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }

}
